"""
应用服务
"""

from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_

from database import get_db

class AppService:
    """应用服务类"""
    
    def __init__(self, db: Session):
        self.db = db
    
    async def get_categories(self) -> List[Dict[str, Any]]:
        """获取应用分类"""
        categories = self.db.query(AppCategoryDB).filter(
            AppCategoryDB.status == 1
        ).order_by(AppCategoryDB.sort_order).all()
        
        return [
            {
                "id": cat.id,
                "name": cat.name,
                "icon": cat.icon,
                "sort_order": cat.sort_order
            }
            for cat in categories
        ]
    
    async def get_apps_list(self, category_id: Optional[int] = None, page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取应用列表"""
        query = self.db.query(ApplicationDB).filter(ApplicationDB.status == 1)
        
        if category_id:
            query = query.filter(ApplicationDB.category_id == category_id)
        
        # 分页
        total = query.count()
        apps = query.order_by(ApplicationDB.sort_order).offset((page - 1) * page_size).limit(page_size).all()
        
        apps_data = []
        for app in apps:
            category = self.db.query(AppCategoryDB).filter(AppCategoryDB.id == app.category_id).first()
            apps_data.append({
                "id": app.id,
                "name": app.name,
                "description": app.description,
                "icon": app.icon,
                "url": str(app.url) if app.url else None,
                "category_id": app.category_id,
                "category_name": category.name if category else None,
                "sort_order": app.sort_order,
                "is_internal": app.is_internal
            })
        
        return {
            "apps": apps_data,
            "total": total,
            "page": page,
            "page_size": page_size,
            "total_pages": (total + page_size - 1) // page_size
        }
    
    async def get_user_favorites(self, user_id: int) -> List[Dict[str, Any]]:
        """获取用户常用应用"""
        favorites = self.db.query(UserAppFavoriteDB, ApplicationDB).join(
            ApplicationDB, UserAppFavoriteDB.app_id == ApplicationDB.id
        ).filter(
            and_(
                UserAppFavoriteDB.user_id == user_id,
                ApplicationDB.status == 1
            )
        ).order_by(UserAppFavoriteDB.sort_order).all()
        
        return [
            {
                "id": app.id,
                "name": app.name,
                "description": app.description,
                "icon": app.icon,
                "url": str(app.url) if app.url else None,
                "sort_order": favorite.sort_order
            }
            for favorite, app in favorites
        ]
    
    async def save_user_favorites(self, user_id: int, app_ids: List[int]) -> None:
        """保存用户常用应用"""
        # 删除现有的常用应用
        self.db.query(UserAppFavoriteDB).filter(UserAppFavoriteDB.user_id == user_id).delete()
        
        # 添加新的常用应用
        for i, app_id in enumerate(app_ids):
            favorite = UserAppFavoriteDB(
                user_id=user_id,
                app_id=app_id,
                sort_order=i + 1
            )
            self.db.add(favorite)
        
        self.db.commit()
    
    async def update_app_sort_order(self, user_id: int, app_orders: List[Dict[str, Any]]) -> None:
        """更新应用排序"""
        for order_data in app_orders:
            app_id = order_data.get("app_id")
            sort_order = order_data.get("sort_order")
            
            favorite = self.db.query(UserAppFavoriteDB).filter(
                and_(
                    UserAppFavoriteDB.user_id == user_id,
                    UserAppFavoriteDB.app_id == app_id
                )
            ).first()
            
            if favorite:
                favorite.sort_order = sort_order
        
        self.db.commit()